import React, { useEffect, useState } from 'react';
import { Form, Input, Select, Radio, Button, Space, Card, Typography, message, Collapse, InputNumber } from 'antd';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import { Agent, AgentFormValues } from '../store/agentTypes';
import { observer } from 'mobx-react-lite';
import { agentStore } from '../store/agentStore';

const { TextArea } = Input;
const { Title } = Typography;
const { Panel } = Collapse;

interface AgentFormProps {
  initialValues?: Agent;
  type?: 'create' | 'edit' | 'view';
  onSubmit: (values: AgentFormValues) => void;
  onCancel: () => void;
}

const AgentForm: React.FC<AgentFormProps> = observer(({ initialValues, type, onSubmit, onCancel }) => {
  const [form] = Form.useForm();
  const [activeParamKeys, setActiveParamKeys] = useState<string[]>([]);
  const [selectedModel, setSelectedModel] = useState<string>('');

  useEffect(() => {
    form.resetFields();
    agentStore.fetchOptions();
    if (initialValues) {
      initialValues.isStreamingBool = initialValues?.isStreaming==='1';
      initialValues.showWelcomeGuideBool = initialValues?.showWelcomeGuide==='1';
      form.setFieldsValue(initialValues);
      setSelectedModel(initialValues.modelId || '');
    }
  }, [initialValues, form]);

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      onSubmit(values);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const handleModelChange = (value: string) => {
    setSelectedModel(value);
  };

  const isViewMode = type === 'view';

  return (
    <Form
      form={form}
      layout="vertical"
      disabled={isViewMode}
      initialValues={initialValues}
      onFinish={handleSubmit}
    >
      {/* 基本信息卡片 */}
      <Card title="基本信息" style={{ marginBottom: 16 }}>
        <Form.Item
          name="name"
          label="智能体名称"
          rules={[{ required: true, message: '请输入智能体名称' }]}
        >
          <Input placeholder="请输入智能体名称" />
        </Form.Item>

        <Form.Item
          name="identifier"
          label="智能体标识"
          rules={[
            { required: true, message: '请输入智能体标识' },
            { pattern: /^[a-zA-Z0-9_]+$/, message: '只能输入英文、数字和下划线' }
          ]}
        >
          <Input placeholder="请输入智能体标识" />
        </Form.Item>

        <Form.Item
          name="modelUsage"
          label="使用模型"
          rules={[{ required: true, message: '请选择使用模型' }]}
        >
          <Select placeholder="请选择使用模型" onChange={handleModelChange}>
            {agentStore.modelOptions.map(model => (
              <Select.Option key={model.value} value={model.value}>
                {model.title}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          name="isStreamingBool"
          label="是否流式输出"
          rules={[{ required: true, message: '请选择是否流式输出' }]}
        >
          <Radio.Group defaultValue={true}>
            <Radio value={true}>是</Radio>
            <Radio value={false}>否</Radio>
          </Radio.Group>
        </Form.Item>
      </Card>

      {/* 模型参数设置卡片 - 使用 Collapse 实现折叠 */}
      {selectedModel && (
        <Collapse
          activeKey={activeParamKeys}
          onChange={setActiveParamKeys}
          style={{ marginBottom: 16 }}
        >
          <Panel header="模型参数设置" key="modelParams">
            <Form.Item
              name="maxTokens"
              label="最大token数"
              rules={[{ type: 'number', min: 1, message: '最大token数必须大于0' }]}
            >
              <InputNumber min={1} style={{ width: '100%' }} placeholder="最大token数必须大于0" />
            </Form.Item>

            <Form.Item
              name="temperature"
              label="温度参数"
              rules={[{ type: 'number', min: 0, max: 2, message: '温度参数必须在0到2之间' }]}
            >
              <InputNumber min={0} max={2} step={0.1} style={{ width: '100%' }} placeholder="温度参数必须在0到2之间" />
            </Form.Item>

            <Form.Item
              name="topP"
              label="top_p参数"
              rules={[{ type: 'number', min: 0, max: 1, message: 'top_p参数必须在0到1之间' }]}
            >
              <InputNumber min={0} max={1} step={0.1} style={{ width: '100%' }} placeholder="top_p参数必须在0到1之间" />
            </Form.Item>

            <Form.Item
              name="frequencyPenalty"
              label="频率惩罚"
              rules={[{ type: 'number', min: -2, max: 2, message: '频率惩罚必须在-2到2之间' }]}
            >
              <InputNumber min={-2} max={2} step={0.1} style={{ width: '100%' }} placeholder="频率惩罚必须在-2到2之间" />
            </Form.Item>

            <Form.Item
              name="presencePenalty"
              label="存在惩罚"
              rules={[{ type: 'number', min: -2, max: 2, message: '存在惩罚必须在-2到2之间' }]}
            >
              <InputNumber min={-2} max={2} step={0.1} style={{ width: '100%' }} placeholder="存在惩罚必须在-2到2之间" />
            </Form.Item>
          </Panel>
        </Collapse>
      )}

      {/* 提示词设置卡片 */}
      <Card title="提示词设置" style={{ marginBottom: 16 }}>
        <Form.Item
          name="backgroundPrompt"
          label="背景提示词"
          rules={[{ required: true, message: '请输入背景提示词' }]}
        >
          <TextArea rows={4} placeholder="请输入背景提示词" />
        </Form.Item>

        <Form.Item
          name="promptTemplate"
          label="提示词模板"
          rules={[{ required: false, message: '请输入提示词模板' }]}
        >
          <TextArea rows={4} placeholder="请输入提示词模板" />
        </Form.Item>
      </Card>

      {/* 知识库设置卡片 */}
      <Card title="知识库设置" style={{ marginBottom: 16 }}>
        <Form.Item
          name="knowledgeUsage"
          label="知识库使用方式"
          rules={[{ required: false, message: '请选择知识库使用方式' }]}
        >
          <Select placeholder="请选择知识库使用方式">
            <Select.Option value="retrieval">召回检索</Select.Option>
            <Select.Option value="direct">直接输出</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="knowledgeBase"
          label="选择知识库"
          rules={[{ required: false, message: '请选择知识库' }]}
        >
          <Select placeholder="请选择知识库" mode="multiple">
            {agentStore.vectorOptions.map(vector => (
              <Select.Option key={vector.id} value={vector.id}>
                {vector.name}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          name="minSimilarity"
          label="最低相似度"
          rules={[{ type: 'number', min: 0, max: 1, message: '相似度必须在0到1之间' }]}
        >
          <InputNumber min={0} max={1} step={0.1} style={{ width: '100%' }} placeholder="0.7" />
        </Form.Item>

        <Form.Item
          name="retrievalCount"
          label="检索数量"
          rules={[{ type: 'number', min: 1, max: 20, message: '检索数量必须在1到20之间' }]}
        >
          <InputNumber min={1} max={20} style={{ width: '100%' }} placeholder="5" />
        </Form.Item>

        <Form.Item
          name="retrievalMethod"
          label="检索方式"
          rules={[{ required: false, message: '请选择检索方式' }]}
        >
          <Select placeholder="请选择检索方式">
            <Select.Option value="normal">常规检索</Select.Option>
            <Select.Option value="metadata">元数据增强</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="enableReranking"
          label="是否启用重排序"
          valuePropName="checked"
        >
          <Radio.Group>
            <Radio value={true}>是</Radio>
            <Radio value={false}>否</Radio>
          </Radio.Group>
        </Form.Item>

        <Form.Item
          name="rerankingModel"
          label="重排序模型"
          rules={[{ required: false, message: '请选择重排序模型' }]}
        >
          <Select placeholder="请选择重排序模型">
            {agentStore.modelOptions.map(model => (
              <Select.Option key={model.value} value={model.value}>
                {model.title}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
      </Card>

      {/* 引导消息卡片 */}
      <Card title="引导消息" style={{ marginBottom: 16 }}>
        <Form.Item name="showWelcomeGuideBool" label="是否显示欢迎引导消息">
          <Radio.Group defaultValue={false} value={initialValues?.showWelcomeGuide==='1'} >
            <Radio value={true}>是</Radio>
            <Radio value={false}>否</Radio>
          </Radio.Group>
        </Form.Item>

        <Form.List name="welcomeMessage">
          {(fields, { add, remove }) => (
            <>
              {fields.map((field, index) => (
                <div key={field.key} style={{ marginBottom: 16 }}>
                  <Space align="baseline">
                    <Form.Item
                      {...field}
                      name={[field.name, 'content']}
                      rules={[{ required: true, message: '请输入引导消息内容' }]}
                    >
                      <Input.TextArea rows={2} placeholder="请输入引导消息内容" />
                    </Form.Item>
                    <Button
                      type="text"
                      danger
                      icon={<DeleteOutlined />}
                      onClick={() => remove(field.name)}
                    />
                  </Space>
                </div>
              ))}
              <Button
                type="dashed"
                onClick={() => add()}
                block
                icon={<PlusOutlined />}
              >
                添加引导消息
              </Button>
            </>
          )}
        </Form.List>
      </Card>

      {/* 文件上传设置卡片 */}
      <Card title="文件上传设置" style={{ marginBottom: 16 }}>
        <Form.Item
          name="fileUpload"
          label="是否允许文件上传"
          rules={[{ required: false, message: '请选择是否允许文件上传' }]}
        >
          <Radio.Group defaultValue={true}>
            <Radio value={true}>是</Radio>
            <Radio value={false}>否</Radio>
          </Radio.Group>
        </Form.Item>
      </Card>

      {/* 函数设置卡片 */}
      <Card title="函数设置" style={{ marginBottom: 16 }}>
        <Form.List name="referenceFunctions">
          {(fields, { add, remove }) => (
            <>
              {fields.map((field, index) => (
                <div key={field.key} style={{ marginBottom: 16 }}>
                  <Space align="baseline">
                    <Form.Item
                      {...field}
                      name={[field.name, 'name']}
                      rules={[{ required: true, message: '请输入函数名称' }]}
                    >
                      <Input placeholder="函数名称" />
                    </Form.Item>
                    <Form.Item
                      {...field}
                      name={[field.name, 'description']}
                      rules={[{ required: true, message: '请输入函数描述' }]}
                    >
                      <Input placeholder="函数描述" />
                    </Form.Item>
                    <Form.Item
                      {...field}
                      name={[field.name, 'functionId']}
                      rules={[{ required: true, message: '请选择函数' }]}
                    >
                      <Select placeholder="选择函数" style={{ width: 200 }}>
                        {agentStore.functionOptions.map(func => (
                          <Select.Option key={func.id} value={func.id}>
                            {func.name}
                          </Select.Option>
                        ))}
                      </Select>
                    </Form.Item>
                    <Button
                      type="text"
                      danger
                      icon={<DeleteOutlined />}
                      onClick={() => remove(field.name)}
                    />
                  </Space>
                </div>
              ))}
              <Button
                type="dashed"
                onClick={() => add()}
                block
                icon={<PlusOutlined />}
              >
                添加引用函数
              </Button>
            </>
          )}
        </Form.List>
      </Card>

      <div style={{ textAlign: 'right', marginTop: 16 }}>
        <Space>
          <Button onClick={onCancel}>取消</Button>
          <Button type="primary" onClick={handleSubmit}>
            保存
          </Button>
        </Space>
      </div>
    </Form>
  );
});

export default AgentForm;